
import {reqCode, reqRegister, reqUserLogin, reqUserInfo, reqLogout} from '@/api';
import { getToken, removeToken, setToken } from '@/utils/token';

export default {
    namespaced: true,
    getters: {
        nickName(state) {
            return state.userInfo.nickName;
        }
    },
    state: {
        code: '',
        token: getToken(),
        userInfo: {},
    },
    actions: {
        async getCode({commit}, phone) {
            let  result = await reqCode(phone);
            if (result.code == 200) {
                commit('GETCODE', result.data);
            }else Promise.reject('faile');
        },
        async check({commit}, data) {
            let result = await reqRegister(data);
            console.log(result);
            if (result.code == 200) {
                return 'ok';
            }else Promise.reject('faile');
        },
        async getLogin({commit}, data) {
            let result = await reqUserLogin(data);
            if (result.code == 200) {
                commit('GETLOGIN', result.data);
            }else Promise.reject('faile');
        },
        async getUserInfo({commit}) {
            let result = await reqUserInfo();
            if (result.code == 200) {
                commit('GETUSERINFO', result.data);
            }
        },
        async getLogout({commit}) {
            let result = await reqLogout();
            if (result.code == 200) {
                // 清除token登录信息
                commit('CLEARUSERINFO');
                // 清除本地存储的token
                removeToken();
                return 'ok';
            }else Promise.reject('faile');
        },
    },
    mutations: {
        GETCODE(state, data) {
            console.log('data' + data);
            state.code = data;
        },
        GETLOGIN(state, data) {
            // 保存token，以免刷新时，token丢失
            setToken(data.token);
            state.token = data.token;
        },
        GETUSERINFO(state, data) {
       //     console.log('userInfo = ' , data);
            state.userInfo = data || {};
        },
        CLEARUSERINFO(state) {
            state.token = '';
            state.userInfo = {};
        }
    }
}